

<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="zh" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="zh" > <!--<![endif]-->
<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <title>optuna.integration.chainer &mdash; Optuna 1.4.0 文档</title>
  

  
  
    <link rel="shortcut icon" href="../../../_static/favicon.ico"/>
  
  
  

  
  <script type="text/javascript" src="../../../_static/js/modernizr.min.js"></script>
  
    
      <script type="text/javascript" id="documentation_options" data-url_root="../../../" src="../../../_static/documentation_options.js"></script>
        <script src="../../../_static/jquery.js"></script>
        <script src="../../../_static/underscore.js"></script>
        <script src="../../../_static/doctools.js"></script>
        <script src="../../../_static/language_data.js"></script>
        <script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
    
    <script type="text/javascript" src="../../../_static/js/theme.js"></script>

    

  
  <link rel="stylesheet" href="../../../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />
  <link rel="stylesheet" href="../../../_static/css/custom.css" type="text/css" />
    <link rel="index" title="索引" href="../../../genindex.html" />
    <link rel="search" title="搜索" href="../../../search.html" /> 
</head>

<body class="wy-body-for-nav">

   
  <div class="wy-grid-for-nav">
    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search" >
          

          
            <a href="../../../index.html" class="icon icon-home"> Optuna
          

          
          </a>

          
            
            
              <div class="version">
                1.4.0
              </div>
            
          

          
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>

          
        </div>

        <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
          
            
            
              
            
            
              <p class="caption"><span class="caption-text">目录</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../installation.html">安装</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../tutorial/index.html">教程</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../reference/index.html">API Reference</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../faq.html">常见问题</a></li>
</ul>

            
          
        </div>
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" aria-label="top navigation">
        
          <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
          <a href="../../../index.html">Optuna</a>
        
      </nav>


      <div class="wy-nav-content">
        
        <div class="rst-content">
        
          















<div role="navigation" aria-label="breadcrumbs navigation">

  <ul class="wy-breadcrumbs">
    
      <li><a href="../../../index.html">Docs</a> &raquo;</li>
        
          <li><a href="../../index.html">模块代码</a> &raquo;</li>
        
      <li>optuna.integration.chainer</li>
    
    
      <li class="wy-breadcrumbs-aside">
        
      </li>
    
  </ul>

  
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
            
  <h1>optuna.integration.chainer 源代码</h1><div class="highlight"><pre>
<span></span><span class="kn">import</span> <span class="nn">optuna</span>
<span class="kn">from</span> <span class="nn">optuna</span> <span class="kn">import</span> <span class="n">type_checking</span>

<span class="k">with</span> <span class="n">optuna</span><span class="o">.</span><span class="n">_imports</span><span class="o">.</span><span class="n">try_import</span><span class="p">()</span> <span class="k">as</span> <span class="n">_imports</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">chainer</span>
    <span class="kn">from</span> <span class="nn">chainer.training.extension</span> <span class="kn">import</span> <span class="n">Extension</span>
    <span class="kn">from</span> <span class="nn">chainer.training</span> <span class="kn">import</span> <span class="n">triggers</span>

<span class="k">if</span> <span class="ow">not</span> <span class="n">_imports</span><span class="o">.</span><span class="n">is_successful</span><span class="p">():</span>
    <span class="n">Extension</span> <span class="o">=</span> <span class="nb">object</span>  <span class="c1"># NOQA</span>

<span class="k">if</span> <span class="n">type_checking</span><span class="o">.</span><span class="n">TYPE_CHECKING</span><span class="p">:</span>
    <span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">Tuple</span>
    <span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">Union</span>

    <span class="n">TriggerType</span> <span class="o">=</span> <span class="n">Union</span><span class="p">[</span>
        <span class="n">Tuple</span><span class="p">[(</span><span class="nb">int</span><span class="p">,</span> <span class="nb">str</span><span class="p">)],</span> <span class="n">triggers</span><span class="o">.</span><span class="n">IntervalTrigger</span><span class="p">,</span> <span class="n">triggers</span><span class="o">.</span><span class="n">ManualScheduleTrigger</span>
    <span class="p">]</span>


<div class="viewcode-block" id="ChainerPruningExtension"><a class="viewcode-back" href="../../../reference/integration.html#optuna.integration.ChainerPruningExtension">[文档]</a><span class="k">class</span> <span class="nc">ChainerPruningExtension</span><span class="p">(</span><span class="n">Extension</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Chainer extension to prune unpromising trials.</span>

<span class="sd">    See `the example &lt;https://github.com/optuna/optuna/blob/master/</span>
<span class="sd">    examples/pruning/chainer_integration.py&gt;`__</span>
<span class="sd">    if you want to add a pruning extension which observes validation</span>
<span class="sd">    accuracy of a `Chainer Trainer &lt;https://docs.chainer.org/en/stable/</span>
<span class="sd">    reference/generated/chainer.training.Trainer.html&gt;`_.</span>

<span class="sd">    Args:</span>
<span class="sd">        trial:</span>
<span class="sd">            A :class:`~optuna.trial.Trial` corresponding to the current evaluation of the</span>
<span class="sd">            objective function.</span>
<span class="sd">        observation_key:</span>
<span class="sd">            An evaluation metric for pruning, e.g., ``main/loss`` and</span>
<span class="sd">            ``validation/main/accuracy``. Please refer to</span>
<span class="sd">            `chainer.Reporter reference &lt;https://docs.chainer.org/en/stable/reference/</span>
<span class="sd">            util/generated/chainer.Reporter.html&gt;`_ for further details.</span>
<span class="sd">        pruner_trigger:</span>
<span class="sd">            A trigger to execute pruning. ``pruner_trigger`` is an instance of</span>
<span class="sd">            `IntervalTrigger &lt;https://docs.chainer.org/en/stable/reference/generated/</span>
<span class="sd">            chainer.training.triggers.IntervalTrigger.html&gt;`_ or</span>
<span class="sd">            `ManualScheduleTrigger &lt;https://docs.chainer.org/en/stable/reference/generated/</span>
<span class="sd">            chainer.training.triggers.ManualScheduleTrigger.html&gt;`_. `IntervalTrigger &lt;https://</span>
<span class="sd">            docs.chainer.org/en/stable/reference/generated/chainer.training.triggers.</span>
<span class="sd">            IntervalTrigger.html&gt;`_ can be specified by a tuple of the interval length and its</span>
<span class="sd">            unit like ``(1, &#39;epoch&#39;)``.</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">trial</span><span class="p">,</span> <span class="n">observation_key</span><span class="p">,</span> <span class="n">pruner_trigger</span><span class="p">):</span>
        <span class="c1"># type: (optuna.trial.Trial, str, TriggerType) -&gt; None</span>

        <span class="n">_imports</span><span class="o">.</span><span class="n">check</span><span class="p">()</span>

        <span class="bp">self</span><span class="o">.</span><span class="n">_trial</span> <span class="o">=</span> <span class="n">trial</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_observation_key</span> <span class="o">=</span> <span class="n">observation_key</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_pruner_trigger</span> <span class="o">=</span> <span class="n">chainer</span><span class="o">.</span><span class="n">training</span><span class="o">.</span><span class="n">get_trigger</span><span class="p">(</span><span class="n">pruner_trigger</span><span class="p">)</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="p">(</span>
            <span class="nb">isinstance</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_pruner_trigger</span><span class="p">,</span> <span class="n">triggers</span><span class="o">.</span><span class="n">IntervalTrigger</span><span class="p">)</span>
            <span class="ow">or</span> <span class="nb">isinstance</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_pruner_trigger</span><span class="p">,</span> <span class="n">triggers</span><span class="o">.</span><span class="n">ManualScheduleTrigger</span><span class="p">)</span>
        <span class="p">):</span>
            <span class="n">pruner_type</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_pruner_trigger</span><span class="p">)</span>
            <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span>
                <span class="s2">&quot;Invalid trigger class: &quot;</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">pruner_type</span><span class="p">)</span> <span class="o">+</span> <span class="s2">&quot;</span><span class="se">\n</span><span class="s2">&quot;</span>
                <span class="s2">&quot;Pruner trigger is supposed to be an instance of &quot;</span>
                <span class="s2">&quot;IntervalTrigger or ManualScheduleTrigger.&quot;</span>
            <span class="p">)</span>

    <span class="nd">@staticmethod</span>
    <span class="k">def</span> <span class="nf">_get_float_value</span><span class="p">(</span><span class="n">observation_value</span><span class="p">):</span>
        <span class="c1"># type: (Union[float, chainer.Variable]) -&gt; float</span>

        <span class="n">_imports</span><span class="o">.</span><span class="n">check</span><span class="p">()</span>

        <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">observation_value</span><span class="p">,</span> <span class="n">chainer</span><span class="o">.</span><span class="n">Variable</span><span class="p">):</span>
            <span class="n">observation_value</span> <span class="o">=</span> <span class="n">observation_value</span><span class="o">.</span><span class="n">data</span>

        <span class="k">try</span><span class="p">:</span>
            <span class="n">observation_value</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="n">observation_value</span><span class="p">)</span>
        <span class="k">except</span> <span class="ne">TypeError</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span>
                <span class="s2">&quot;Type of observation value is not supported by ChainerPruningExtension.</span><span class="se">\n</span><span class="s2">&quot;</span>
                <span class="s2">&quot;</span><span class="si">{}</span><span class="s2"> cannot be cast to float.&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="nb">type</span><span class="p">(</span><span class="n">observation_value</span><span class="p">))</span>
            <span class="p">)</span>

        <span class="k">return</span> <span class="n">observation_value</span>

    <span class="k">def</span> <span class="nf">_observation_exists</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">trainer</span><span class="p">):</span>
        <span class="c1"># type: (chainer.training.Trainer) -&gt; bool</span>

        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_pruner_trigger</span><span class="p">(</span><span class="n">trainer</span><span class="p">)</span> <span class="ow">and</span> <span class="bp">self</span><span class="o">.</span><span class="n">_observation_key</span> <span class="ow">in</span> <span class="n">trainer</span><span class="o">.</span><span class="n">observation</span>

    <span class="k">def</span> <span class="fm">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">trainer</span><span class="p">):</span>
        <span class="c1"># type: (chainer.training.Trainer) -&gt; None</span>

        <span class="k">if</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">_observation_exists</span><span class="p">(</span><span class="n">trainer</span><span class="p">):</span>
            <span class="k">return</span>

        <span class="n">current_score</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_get_float_value</span><span class="p">(</span><span class="n">trainer</span><span class="o">.</span><span class="n">observation</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">_observation_key</span><span class="p">])</span>
        <span class="n">current_step</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">trainer</span><span class="o">.</span><span class="n">updater</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">_pruner_trigger</span><span class="o">.</span><span class="n">unit</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_trial</span><span class="o">.</span><span class="n">report</span><span class="p">(</span><span class="n">current_score</span><span class="p">,</span> <span class="n">step</span><span class="o">=</span><span class="n">current_step</span><span class="p">)</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_trial</span><span class="o">.</span><span class="n">should_prune</span><span class="p">():</span>
            <span class="n">message</span> <span class="o">=</span> <span class="s2">&quot;Trial was pruned at </span><span class="si">{}</span><span class="s2"> </span><span class="si">{}</span><span class="s2">.&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_pruner_trigger</span><span class="o">.</span><span class="n">unit</span><span class="p">,</span> <span class="n">current_step</span><span class="p">)</span>
            <span class="k">raise</span> <span class="n">optuna</span><span class="o">.</span><span class="n">TrialPruned</span><span class="p">(</span><span class="n">message</span><span class="p">)</span></div>
</pre></div>

           </div>
           
          </div>
          <footer>
  

  <hr/>

  <div role="contentinfo">
    <p>
        &copy; Copyright 2018, Optuna Contributors.

    </p>
  </div>
  Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/rtfd/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
    <a href="../../../privacy.html">Privacy Policy</a>.
     


</footer>

        </div>
      </div>

    </section>

  </div>
  


  <script type="text/javascript">
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(true);
      });
  </script>

  
  
    
    <!-- Theme Analytics -->
    <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-55135190-8', 'auto');
    ga('send', 'pageview');
    </script>

    
   

</body>
</html>